#pragma once

#include <INA226.h>
#include "MPPT.h"

INA226 INA1(0x40); // 光伏电池输出功率检测
INA226 INA3(0x44); // 铅酸电池充电功率检测

// 创建MUTEX进行结构体共享数据保护
SemaphoreHandle_t xMutexSensor = NULL; // 创建信号量Handler
TickType_t timeOut = 3000;             // 用于获取信号量的Timeout 1000 ticks

/*NTC热敏电阻，检测PCB温度*/
void PCB_temp(void *pt)
{
    TickType_t xLastWakeTime = xTaskGetTickCount(); // 相当于millis, typedef uint32_t TickType_t;
    const TickType_t xFrequency = 3000;             // 间隔 3000 ticks = 3 seconds

    const float R1 = 10.0;       //  NTC热敏电阻的值，25℃，10K
    const float B = 3334;        // 热敏电阻的B值，25~50℃为3380，25~85℃为3334
    const float T = 273.15 + 25; // 参考温度

    while (1)
    {
        vTaskDelayUntil(&xLastWakeTime, xFrequency); // 定时，3s执行一次
        // Serial.println(xTaskGetTickCount()); // 验证时间间隔

        if (xSemaphoreTake(xMutexSensor, timeOut) == pdPASS)
        {
            int ntcValue = analogRead(NTC_PIN);
            float Rt = (4095.0 / (float)ntcValue - 1.0) * R1;         // 计算NTC电阻值
            data.tempC = ((T * B) / (B + T * log(Rt / R1))) - 273.15; // // 计算温度值（单位：摄氏度）
            xSemaphoreGive(xMutexSensor);                             // 释放钥匙
        }
        else
        {
            // Unable to obtain MUTEX
        }
        // 输出温度值
        Serial.print("Temperature = ");
        Serial.print(data.tempC);
        Serial.println(" °C");
    }
}

//////////////////////////////////////////////////////////////////
void MPPT(void *pt)
{
    pinMode(PWM_ENABLE_PIN, OUTPUT);
    TURN_OFF_MOSFETS;
    charger_state = off;

    pinMode(LOAD_PIN, OUTPUT);
    digitalWrite(LOAD_PIN, LOW); // 关闭负载输出

    /*LEDC输出PWM配置*/
    ledcSetup(pwmChannel, pwmFrequency, pwmResolution);
    ledcAttachPin(PWM_PIN, pwmChannel); // 绑定PWM输出引脚到通道0
    ledcWrite(pwmChannel, PWM);
    int PWM_MAX = pow(2, pwmResolution) - 1; // PWM理论输出最大值2047

    PWM = PWM_start; // 初始PWM值

    INA1.setMaxCurrentShunt(8, 0.01); // 最大电流A,采样电阻0.01R
    INA3.setMaxCurrentShunt(8, 0.01);
    while (1)
    {
        if (xSemaphoreTake(xMutexSensor, timeOut) == pdPASS)
        {
            data.Solar_V = INA1.getBusVoltage();
            data.Solar_I = INA1.getCurrent();
            data.Solar_P = INA1.getPower();

            data.Charge_V = INA3.getBusVoltage();
            data.Charge_I = INA3.getCurrent();
            data.Charge_P = INA3.getPower();
            xSemaphoreGive(xMutexSensor); // 释放钥匙
        }
        else
        {
            // Unable to obtain MUTEX
        }
        run_charger(); // MPPT充电控制
    }
}